/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2015-07-29     Arda.Fu      first implementation
 */
#include <stdint.h>
#include <rtthread.h>
#include <rtdevice.h>
#include "n32g45x_gpio.h"
//#include "wifiservice.h"
#include "ws2812b.h"
#include "dht11service.h"

extern int wifi_service_init();

/* defined the LED1 pin: PB5 */
#define LED1_PIN    57 //g
#define LED2_PIN    56 //b
#define LED3_PIN    41 //r
#define KEYWK_PIN   14 //key3
#define LED_SPEED   500

void led_service_thread(void *param)
{
    rt_kprintf("led_service_thread start.\n");
    while (1)
    {
        rt_pin_write(LED1_PIN, PIN_LOW);
        rt_thread_mdelay(LED_SPEED);
        rt_pin_write(LED1_PIN, PIN_HIGH);
        rt_thread_mdelay(LED_SPEED);
    }
}
void wifi_led_set(char status)
{
    if(status)
    {
        rt_pin_write(LED2_PIN, PIN_HIGH);
    }
    else
    {
        rt_pin_write(LED2_PIN, PIN_LOW);
    }
}
void server_led_set(char status)
{
    if(status)
    {
        rt_pin_write(LED3_PIN, PIN_HIGH);
    }
    else
    {
        rt_pin_write(LED3_PIN, PIN_LOW);
    }
}
extern int switchstatus;
void key_service_thread(void *param)
{
    rt_kprintf("key_service_thread start.\n");
    while (1)
    {
        if(rt_pin_read(KEYWK_PIN)==1)
        {
            rt_thread_mdelay(100);
            if(rt_pin_read(KEYWK_PIN)==1)
            {
                rt_kprintf("KEYWK_PIN DOWN.\n");
                while (rt_pin_read(KEYWK_PIN))
                {
                    rt_thread_mdelay(50);
                }
                switchstatus = !switchstatus;
            }
        }
        rt_thread_mdelay(50);
    }
}
void pin_init()
{
    /* set LED1 pin mode to output */
    rt_pin_mode(LED1_PIN, PIN_MODE_OUTPUT);
    RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_AFIO,ENABLE);
    GPIO_ConfigPinRemap(GPIO_RMP_SW_JTAG_SW_ENABLE, ENABLE);
    rt_pin_mode(LED2_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LED3_PIN, PIN_MODE_OUTPUT);
    rt_pin_write(LED2_PIN, PIN_LOW);
    rt_pin_write(LED3_PIN, PIN_LOW);

    rt_pin_mode(KEYWK_PIN, PIN_MODE_INPUT);

    rt_thread_t ledservice_thread = rt_thread_create("led",led_service_thread,RT_NULL,1024,29,20);
    if (ledservice_thread != RT_NULL)
    {
        rt_thread_startup(ledservice_thread);
    }
    else
    {
        rt_kprintf("ledservice_thread create failed.\n");
    }

    rt_thread_t keyservice_thread = rt_thread_create("key",key_service_thread,RT_NULL,1024,29,20);
    if (keyservice_thread != RT_NULL)
    {
        rt_thread_startup(keyservice_thread);
    }
    else
    {
        rt_kprintf("keyservice_thread create failed.\n");
    }
}
int main(void)
{
    pin_init();
    wifi_service_init();
    dht11service_init();
    ws2812_led_init();

    while (1)
    {    
        rt_thread_mdelay(500);
    }
}
